package com.why.biyesheji.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.why.biyesheji.dao.CategoryMapper;
import com.why.biyesheji.pojo.Category;
import com.why.biyesheji.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Created by 华耀 王 on 2020/12/20
 **/
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /*
     * 递归查询本节点的id及子节点的id
     * */
    @Override
    public List<Integer> selectCategoryAndChildById(Integer categoryId) {
        Set<Category> categorySet = Sets.newHashSet();
        findChildCategory(categorySet,categoryId);

        List<Integer> categoryList =Lists.newArrayList();
        if (categoryId != null){
            for (Category categoryItem : categorySet) {
                categoryList.add(categoryItem.getId());
            }
        }
        return categoryList;
    }

    private Set<Category> findChildCategory(Set<Category> categorySet, Integer categoryId) {
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category != null){
            categorySet.add(category);
        }

        //查找子节点，递归算法一定要有一个退出的条件
        // 根据父节点查询其下的所有子节点，并递归调用findChildCategory方法

//        使用Mybatis根据条件查询数据,没有查询到数据时返回的值类型,
//        一: 如果使用的是集合接收(如List),没有查询到数据时,返回的是空集合既size为0的集合,
//        二: 使用对象接收,没有查询到数据时返回的值为:null
        List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
        for (Category categoryItem : categoryList) {
            findChildCategory(categorySet,categoryItem.getId());
        }
        return categorySet;
    }

}
